/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * SunSpotServicesView.java
 *
 * Created on 23-may-2012, 17:55:23
 */
package org.sunspotUI;

import java.awt.Color;
import java.io.File;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import org.sunspotworld.Service;
import org.sunspotworld.SunSpotHostApplication;

/**
 *
 * @author Migue
 */
public class SunSpotServicesView extends javax.swing.JFrame {
    private final SunSpotHostApplication sha;

    /** Creates new form SunSpotServicesView */
    public SunSpotServicesView() {
        initComponents();
        if(services == null){
            services = new Hashtable<String, List<Service>>();
        }
        sha = null;
    }

    public SunSpotServicesView(SunSpotHostApplication sha) {
        initComponents();
        this.sha = sha;
        if(services == null){
            services = new Hashtable<String, List<Service>>();
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        PanelServices = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tableServices = new javax.swing.JTable();
        jToolBar1 = new javax.swing.JToolBar();
        removeButton = new javax.swing.JButton();
        removeAllButton = new javax.swing.JButton();
        statusLabel = new javax.swing.JLabel();

        setTitle("SunSpot Services");

        PanelServices.setBorder(javax.swing.BorderFactory.createTitledBorder("Services"));

        tableServices.setAutoCreateRowSorter(true);
        tableServices.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Type", "Name", "Owner"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            @Override
            public boolean isCellEditable(int row, int column) {
                //all cells false
                return false;
            }
        });
        tableServices.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        tableServices.setEnabled(true);
        tableServices.setFocusable(false);
        jScrollPane1.setViewportView(tableServices);

        javax.swing.GroupLayout PanelServicesLayout = new javax.swing.GroupLayout(PanelServices);
        PanelServices.setLayout(PanelServicesLayout);
        PanelServicesLayout.setHorizontalGroup(
            PanelServicesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1)
        );
        PanelServicesLayout.setVerticalGroup(
            PanelServicesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 366, Short.MAX_VALUE)
        );

        jToolBar1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 255, 255), 1, true));
        jToolBar1.setRollover(true);

        File f = new File("");
        String sep = System.getProperty("file.separator");
        String s = f.getAbsolutePath()+sep+"build"+sep+"org"+sep+"images"+sep+"Remove one.png";
        removeButton.setIcon(new javax.swing.ImageIcon(s));
        removeButton.setToolTipText("Remove Service");
        removeButton.setFocusable(false);
        removeButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        removeButton.setMaximumSize(new java.awt.Dimension(39, 39));
        removeButton.setMinimumSize(new java.awt.Dimension(39, 39));
        removeButton.setPreferredSize(new java.awt.Dimension(39, 39));
        removeButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        removeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(removeButton);

        f = new File("");
        s = f.getAbsolutePath()+sep+"build"+sep+"org"+sep+"images"+sep+"Remove all.png";
        removeAllButton.setIcon(new javax.swing.ImageIcon(s));
        removeAllButton.setToolTipText("Remove All Services");
        removeAllButton.setFocusable(false);
        removeAllButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        removeAllButton.setMaximumSize(new java.awt.Dimension(39, 39));
        removeAllButton.setMinimumSize(new java.awt.Dimension(39, 39));
        removeAllButton.setPreferredSize(new java.awt.Dimension(39, 39));
        removeAllButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        removeAllButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeAllButtonActionPerformed(evt);
            }
        });
        jToolBar1.add(removeAllButton);

        statusLabel.setToolTipText("Status Services");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(statusLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 507, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(PanelServices, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(statusLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(PanelServices, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void removeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeButtonActionPerformed
        // TODO add your handling code here:
        DefaultTableModel model = (DefaultTableModel) tableServices.getModel();
        int[] rows = tableServices.getSelectedRows();
        Map <String,Service> serviceSelected;
        this.statusServices("",null);
        
        for(int i=0;i<rows.length;i++){
            serviceSelected = this.getRowDataAsMap(rows[i]);
            removeService(serviceSelected);
        }
    }//GEN-LAST:event_removeButtonActionPerformed

    private void removeAllButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeAllButtonActionPerformed
        // TODO add your handling code here:
        this.statusServices("",null);
        if(services!=null && !services.isEmpty()){
            sha.unregisterAllServicesAux();
        }
    }//GEN-LAST:event_removeAllButtonActionPerformed
    
    private Map <String,Service> getRowDataAsMap(int rowIndex)
    {
        Map <String,Service>  retVal = new HashMap <String, Service>();
        DefaultTableModel model = (DefaultTableModel) tableServices.getModel();
        String [] rowData = this.getRowData(rowIndex);
        List<String> colData = this.getColumnNames();
        Service serv = new Service();
        String type, name, owner;
        
        type = getValueforCell(rowIndex, colData.indexOf("Type"));
        name = getValueforCell(rowIndex, colData.indexOf("Name"));
        owner = getValueforCell(rowIndex, colData.indexOf("Owner"));
        retVal.put(type, new Service(name,owner));
        
        return retVal;
    }
    
    private String[] getRowData(int rowIndex)
    {
        if ((rowIndex >  tableServices.getRowCount()) || (rowIndex  <  0))
        {
            return null;
        }
        ArrayList <String>  data = new ArrayList <String>();
        for (int c = 0; c  <  tableServices.getColumnCount(); c++)
        {
            data.add((String) this.getValueforCell(rowIndex, c));
        }
        String[] retVal = new String[data.size()];
        for (int i = 0; i  <  retVal.length; i++)
        {
            retVal[i] = data.get(i);
        }

        return retVal;
    }
    
    private String getValueforCell(int row, int col)
    {
        return (String) tableServices.getModel().getValueAt(row, col).toString();
    }
    
    private List<String> getColumnNames()
    {
        List<String> colNames = new LinkedList<String>();
        for (int i = 0; i  <  tableServices.getColumnCount(); i++)
        {
            colNames.add(tableServices.getColumnName(i));
        }
        return colNames;
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(SunSpotServicesView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SunSpotServicesView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SunSpotServicesView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SunSpotServicesView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new SunSpotServicesView().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel PanelServices;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JButton removeAllButton;
    private javax.swing.JButton removeButton;
    private javax.swing.JLabel statusLabel;
    private javax.swing.JTable tableServices;
    // End of variables declaration//GEN-END:variables
    
    Hashtable<String, List<Service>> services;  
    
    protected void addServicesTable(Hashtable<String, List<Service>> services) {
        this.services = services;
        loadTable();
    }

    private void loadTable() {
        Enumeration<String> keys=services.keys();
        Boolean end=false;
        String key;
        int i = 0;
        List<Service> ser;
        String type="";
        String name="";
        String owner="";
        
        //this.initComponents();
        DefaultTableModel model = (DefaultTableModel) tableServices.getModel();
        while (model.getRowCount()>0){
            model.removeRow(0);
        }
        //model.getDataVector().removeAllElements();
        
        while(!end && keys.hasMoreElements()){
            key=keys.nextElement();
            type = key;
            ser=this.services.get(key);
            i=0;
            while(!end && i<ser.size()){
                name = ser.get(i).getName();
                owner = ser.get(i).getOwner();
                model.addRow(new Object[]{type,name,owner});
                i++;
            }
        }
    }

    private void removeService(Map<String, Service> serviceSelected) {
        Enumeration<String> keys=services.keys();
        Boolean end = false;
        String key = null;
        int i = 0;
        List<Service> ser;
        Service service = null;
        
        while(!end && keys.hasMoreElements()){
            key=keys.nextElement();
            ser=this.services.get(key);
            if(serviceSelected.containsKey(key)){
                Iterator it = ser.iterator();
                while (!end && it.hasNext()){
                    Service aux = (Service) it.next();
                    end = serviceSelected.get(key).equals(aux);
                    service = aux;
                }
            }  
        }
        
        if(end) sha.unregisterServiceAux(key, service.getName());
        if(tableServices.getRowCount()>0){
            tableServices.changeSelection(0, -1, false, false);
            tableServices.requestFocus();
        }
    }

    protected void statusServices(String message, Color c) {
        statusLabel.setForeground(c);
        statusLabel.setText(message);
    }
}
